package com.qianmang.damawangticket.utils;

import android.accessibilityservice.AccessibilityService;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.Toast;

import androidx.annotation.Keep;
import androidx.annotation.Nullable;

import com.qianmang.damawangticket.bean.AppBean;
import com.qianmang.damawangticket.service.MyAccessibilityService;

import java.util.List;
import java.util.Random;

public class ControllerUtils {



    /**
     * 根据控件的内容 查找View，点击该View
     *
     * @param viewContent 控件的文本
     * @param clazz       控件的Class
     */
    public static void findTextAndClick(AccessibilityService accessibilityService, String viewContent, Class<? extends View> clazz) {

        AccessibilityNodeInfo accessibilityNodeInfo = accessibilityService.getRootInActiveWindow();
        if (accessibilityNodeInfo == null) {
            return;
        }
        List<AccessibilityNodeInfo> nodeInfoList = accessibilityNodeInfo.findAccessibilityNodeInfosByText(viewContent);
        if (nodeInfoList != null && !nodeInfoList.isEmpty()) {
            for (AccessibilityNodeInfo nodeInfo : nodeInfoList) {
                if (nodeInfo != null && nodeInfo.getClassName().equals(clazz.getName())) {
                    performClick(nodeInfo);
                    break;
                }
            }
        }
    }

    /**
     * 根据控件的内容 查找View，点击该View
     *
     * @param viewContent 控件的文本
     * @param index       index为-1时则表示获取最后一个元素
     */
    public static void findTextAndClick(AccessibilityService accessibilityService, String viewContent, int index) {

        AccessibilityNodeInfo accessibilityNodeInfo = accessibilityService.getRootInActiveWindow();
        if (accessibilityNodeInfo == null) {
            return;
        }
        List<AccessibilityNodeInfo> nodeInfoList = accessibilityNodeInfo.findAccessibilityNodeInfosByText(viewContent);
        if (nodeInfoList != null) {
            int size = nodeInfoList.size();
            if (index == -1) {
                performClick(accessibilityService, nodeInfoList.get(size - 1));
            } else if (index < nodeInfoList.size()) {
                performClick(accessibilityService, nodeInfoList.get(index));
            }
        }
    }

    /**
     * 根据控件的内容 查找View，点击该View
     *
     * @param viewContent 控件的文本
     * @param clazz       控件的Class
     */
    public static void findLastTextAndClick(AccessibilityService accessibilityService, String viewContent, Class<? extends View> clazz) {

        AccessibilityNodeInfo accessibilityNodeInfo = accessibilityService.getRootInActiveWindow();
        if (accessibilityNodeInfo == null) {
            return;
        }
        List<AccessibilityNodeInfo> nodeInfoList = accessibilityNodeInfo.findAccessibilityNodeInfosByText(viewContent);
        if (nodeInfoList != null && !nodeInfoList.isEmpty()) {
            AccessibilityNodeInfo nodeInfo1 = nodeInfoList.get(nodeInfoList.size() - 1);
            if (nodeInfo1 != null && nodeInfo1.getClassName().equals(clazz.getName())) {
                performClick(nodeInfo1);
            }
        }
    }


    /**
     * 通过View id判断该View是否存在
     *
     * @param accessibilityService
     * @param id
     */
    public static boolean isViewExist(AccessibilityService accessibilityService, String id) {

        AccessibilityNodeInfo accessibilityNodeInfo = accessibilityService.getRootInActiveWindow();
        if (accessibilityNodeInfo == null) {
            return false;
        }

        List<AccessibilityNodeInfo> nodeInfoList = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId(id);
        return nodeInfoList != null && !nodeInfoList.isEmpty();
    }

    /**
     * 通过View id判断该View是否存在
     *
     * @param accessibilityService
     * @param viewName
     */
    public static boolean isViewExistByName(AccessibilityService accessibilityService, String viewName) {

        AccessibilityNodeInfo accessibilityNodeInfo = accessibilityService.getRootInActiveWindow();
        if (accessibilityNodeInfo == null) {
            return false;
        }

        List<AccessibilityNodeInfo> nodeInfoList = accessibilityNodeInfo.findAccessibilityNodeInfosByText(viewName);
        return nodeInfoList != null && !nodeInfoList.isEmpty();
    }

    /**
     * 检查viewId进行向前滑动
     *
     * @param accessibilityService
     * @param id
     */
    public static void findViewIdAndScrollForward(AccessibilityService accessibilityService, String id) {

        AccessibilityNodeInfo accessibilityNodeInfo = accessibilityService.getRootInActiveWindow();
        if (accessibilityNodeInfo == null) {
            return;
        }

        List<AccessibilityNodeInfo> nodeInfoList = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId(id);
        if (nodeInfoList != null && !nodeInfoList.isEmpty()) {
            for (AccessibilityNodeInfo nodeInfo : nodeInfoList) {
                if (nodeInfo != null) {
                    performScrollForward(nodeInfo);
                    break;
                }
            }
        }
    }


    /**
     * 检查viewId进行点击
     *
     * @param accessibilityService
     * @param id
     */
    public static void findViewIdAndClick(AccessibilityService accessibilityService, String id) {

        AccessibilityNodeInfo accessibilityNodeInfo = accessibilityService.getRootInActiveWindow();
        if (accessibilityNodeInfo == null) {
            return;
        }

        List<AccessibilityNodeInfo> nodeInfoList = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId(id);
        if (nodeInfoList != null && !nodeInfoList.isEmpty()) {
            for (AccessibilityNodeInfo nodeInfo : nodeInfoList) {
                if (nodeInfo != null) {
                    performClick(nodeInfo);
                    break;
                }
            }
        }
    }

    /**
     * 当搜索出来多个的时候，指定index进行模拟点击
     *
     * @param accessibilityService
     * @param id
     * @param index
     */
    public static void findViewIdAndClick(AccessibilityService accessibilityService, String id, int index) {

        AccessibilityNodeInfo accessibilityNodeInfo = accessibilityService.getRootInActiveWindow();
        if (accessibilityNodeInfo == null) {
            return;
        }

        List<AccessibilityNodeInfo> nodeInfoList = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId(id);
        if (nodeInfoList != null && nodeInfoList.size() > index) {
            performClick(nodeInfoList.get(index));
        }
    }


    /**
     * 查找控件，并将焦点放在该空间上
     *
     * @param accessibilityService
     * @param id
     */
    public static void findViewIdAndFouce(AccessibilityService accessibilityService, String id) {

        AccessibilityNodeInfo accessibilityNodeInfo = accessibilityService.getRootInActiveWindow();
        if (accessibilityNodeInfo == null) {
            return;
        }

        List<AccessibilityNodeInfo> nodeInfoList = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId(id);
        if (nodeInfoList != null && !nodeInfoList.isEmpty()) {
            for (AccessibilityNodeInfo nodeInfo : nodeInfoList) {
                if (nodeInfo != null) {
                    nodeInfo.performAction(AccessibilityNodeInfo.ACTION_FOCUS);
                    break;
                }
            }
        }
    }


    /**
     * 根据id查找控件，并将内容粘贴上去
     *
     * @param accessibilityService
     * @param id                   控件id
     * @param content              文本内容
     * @return true 表示粘贴成功 false 表示文本粘贴失败
     */
    @Keep
    public static boolean findViewByIdAndPasteContent(AccessibilityService accessibilityService, String id, String content) {
        AccessibilityNodeInfo rootNode = accessibilityService.getRootInActiveWindow();
        if (rootNode != null) {
            List<AccessibilityNodeInfo> editInfo = rootNode.findAccessibilityNodeInfosByViewId(id);
            if (editInfo != null && !editInfo.isEmpty()) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    Bundle arguments = new Bundle();
                    arguments.putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, content);
                    performClick(editInfo.get(0));
                    editInfo.get(0).performAction(AccessibilityNodeInfo.ACTION_FOCUS);
                    editInfo.get(0).performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, arguments);
                    return true;
                } else {
                    Bundle arguments = new Bundle();
                    arguments.putInt(AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT,
                            AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD);
                    arguments.putBoolean(AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN, true);
                    editInfo.get(0).performAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY, arguments);
                    editInfo.get(0).performAction(AccessibilityNodeInfo.ACTION_FOCUS);
                    ClipboardManager clipboardManager = (ClipboardManager) accessibilityService.getSystemService(Context.CLIPBOARD_SERVICE);
                    ClipData clip = ClipData.newPlainText("label", content);
                    clipboardManager.setPrimaryClip(clip);
                    editInfo.get(0).performAction(AccessibilityNodeInfo.ACTION_PASTE); //粘贴内容
                }
                return true;
            }
            return false;
        }
        return false;
    }

    /**
     * 根据id查找控件上的文字描述
     *
     * @param accessibilityService
     * @param id
     * @return
     */
    public static String findTextById(AccessibilityService accessibilityService, String id) {
        AccessibilityNodeInfo rootInfo = accessibilityService.getRootInActiveWindow();
        if (rootInfo != null) {
            List<AccessibilityNodeInfo> userNames = rootInfo.findAccessibilityNodeInfosByViewId(id);
            if (userNames != null && userNames.size() > 0) {
                CharSequence text = userNames.get(0).getText();
                if (!TextUtils.isEmpty(text)) {
                    return text.toString();
                }
                return null;
            }
        }
        return null;
    }


    /**
     * 在当前页面查找对话框文字内容并点击
     *
     * @param text1 默认点击text1
     * @param text2
     */
    public static void findDialogAndClick(AccessibilityService accessibilityService, String text1, String text2) {

        AccessibilityNodeInfo accessibilityNodeInfo = accessibilityService.getRootInActiveWindow();
        if (accessibilityNodeInfo == null) {
            return;
        }

        List<AccessibilityNodeInfo> dialogWait = accessibilityNodeInfo.findAccessibilityNodeInfosByText(text1);
        List<AccessibilityNodeInfo> dialogConfirm = accessibilityNodeInfo.findAccessibilityNodeInfosByText(text2);
        if (!dialogWait.isEmpty() && !dialogConfirm.isEmpty()) {
            for (AccessibilityNodeInfo nodeInfo : dialogWait) {
                if (nodeInfo != null && text1.equals(nodeInfo.getText())) {
                    performClick(nodeInfo);
                    break;
                }
            }
        }
    }

    /**
     * 将内容粘贴到对应的控件上
     *
     * @param accessibilityService
     * @param nodeInfo
     * @param content
     */
    @Keep
    public static void pastContent(AccessibilityService accessibilityService, @Nullable AccessibilityNodeInfo nodeInfo, String content) {
        if (accessibilityService == null || TextUtils.isEmpty(content) || nodeInfo == null) return;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Bundle arguments = new Bundle();
            arguments.putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, content);
            nodeInfo.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, arguments);
        } else {
            Bundle arguments = new Bundle();
            arguments.putInt(AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT,
                    AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD);
            arguments.putBoolean(AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN, true);
            nodeInfo.performAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY, arguments);
            nodeInfo.performAction(AccessibilityNodeInfo.ACTION_FOCUS);
            ClipboardManager clipboardManager = (ClipboardManager) accessibilityService.getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("label", content);
            clipboardManager.setPrimaryClip(clip);
            nodeInfo.performAction(AccessibilityNodeInfo.ACTION_PASTE); //粘贴内容


        }
        nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);

    }

    //模拟点击事件
    public static void performClick(AccessibilityNodeInfo nodeInfo) {
        if (nodeInfo == null) {
            return;
        }
        if (nodeInfo.isClickable()) {
            nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
        } else {
            performClick(nodeInfo.getParent()); //递归调用
        }
    }


    //模拟点击事件
    public static void performClick(AccessibilityService accessibilityService, AccessibilityNodeInfo nodeInfo) {
        if (nodeInfo == null) {
            return;
        }
        if (nodeInfo.isEnabled()) {
            Rect rect = new Rect();
            nodeInfo.getBoundsInScreen(rect);
            int x = (rect.left + rect.right) / 2;
            int y = (rect.top + rect.bottom) / 2;
            CommandExecution.click(accessibilityService, x, y, null);
        } else {
            performClick(accessibilityService, nodeInfo.getParent()); //递归调用
        }
    }

    //模拟向前滑动事件
    public static void performScrollForward(AccessibilityNodeInfo nodeInfo) {
        if (nodeInfo == null) {
            return;
        }

        if (nodeInfo.isScrollable()) {
            nodeInfo.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
        } else {
            performScrollForward(nodeInfo.getParent());
        }
    }

    //模拟向后滑动事件
    public static void performScrollBackward(AccessibilityNodeInfo nodeInfo) {
        if (nodeInfo == null) {
            return;
        }

        if (nodeInfo.isScrollable()) {
            nodeInfo.performAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
        } else {
            performScrollForward(nodeInfo.getParent());
        }
    }

    /**
     *
     * @param nodeInfo
     * @param orientation  参看{@link AccessibilityNodeInfo.AccessibilityAction}
     */
    public static void performScroll(AccessibilityNodeInfo nodeInfo, int orientation) {
        if (nodeInfo == null) {
            return;
        }

        if (nodeInfo.isScrollable()) {
            nodeInfo.performAction(orientation);
        } else {
            performScroll(nodeInfo.getParent(), orientation);
        }
    }

    //模拟系统返回事件
    public static void performSystemBack(AccessibilityService service) {
        if (service == null) {
            return;
        }
        boolean b = service.performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
    }


    /**
     * 判断微信助手是否开启
     *
     * @param context
     * @return
     */
    public static boolean isAccessibilitySettingsOn(Context context) {
        int accessibilityEnabled = 0;
        try {
            accessibilityEnabled = Settings.Secure.getInt(context.getContentResolver(),
                    Settings.Secure.ACCESSIBILITY_ENABLED);
        } catch (Settings.SettingNotFoundException e) {
            Log.i("URL", "错误信息为：" + e.getMessage());
        }

        if (accessibilityEnabled == 1) {
            String services = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
            if (services != null) {
                return services.toLowerCase().contains(context.getPackageName().toLowerCase());
            }
        }
        return false;
    }


    @Nullable
    public static AccessibilityNodeInfo findViewById(AccessibilityService controlService, String viewId) {
        AccessibilityNodeInfo accessibilityNodeInfo = controlService.getRootInActiveWindow();
        if (accessibilityNodeInfo == null) {
            return null;
        }

        List<AccessibilityNodeInfo> nodeInfoList = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId(viewId);
        if (nodeInfoList != null && !nodeInfoList.isEmpty()) {
            for (AccessibilityNodeInfo nodeInfo : nodeInfoList) {
                return nodeInfo;
            }
        }
        return null;
    }

    @Nullable
    public static List<AccessibilityNodeInfo> findViewsById(AccessibilityService controlService, String viewId) {
        AccessibilityNodeInfo accessibilityNodeInfo = controlService.getRootInActiveWindow();
        if (accessibilityNodeInfo == null) {
            return null;
        }

        List<AccessibilityNodeInfo> nodeInfoList = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId(viewId);
        if (nodeInfoList != null && !nodeInfoList.isEmpty()) {
            return nodeInfoList;
        }
        return null;
    }

    public static AccessibilityNodeInfo findViewByText(AccessibilityService controlService, String viewText) {
        AccessibilityNodeInfo accessibilityNodeInfo = controlService.getRootInActiveWindow();
        if (accessibilityNodeInfo == null) {
            return null;
        }

        List<AccessibilityNodeInfo> nodeInfoList = accessibilityNodeInfo.findAccessibilityNodeInfosByText(viewText);
        if (nodeInfoList != null && !nodeInfoList.isEmpty()) {
            for (AccessibilityNodeInfo nodeInfo : nodeInfoList) {
                return nodeInfo;
            }
        }
        return null;
    }


    public static AccessibilityNodeInfo findViewByText(AccessibilityService controlService, String viewText, Class<? extends View> clazz) {
        AccessibilityNodeInfo accessibilityNodeInfo = controlService.getRootInActiveWindow();
        if (accessibilityNodeInfo == null) {
            return null;
        }

        List<AccessibilityNodeInfo> nodeInfoList = accessibilityNodeInfo.findAccessibilityNodeInfosByText(viewText);
        if (nodeInfoList != null && !nodeInfoList.isEmpty()) {
            for (AccessibilityNodeInfo nodeInfo : nodeInfoList) {
                if(nodeInfo != null && nodeInfo.getClassName().equals(clazz.getName())){
                    return nodeInfo;
                }
            }
        }
        return null;
    }

    public static List<AccessibilityNodeInfo> findViewByTexts(AccessibilityService controlService, String viewText) {
        AccessibilityNodeInfo accessibilityNodeInfo = controlService.getRootInActiveWindow();
        if (accessibilityNodeInfo == null) {
            return null;
        }
        return accessibilityNodeInfo.findAccessibilityNodeInfosByText(viewText);
    }

    public static AccessibilityNodeInfo findViewByText(AccessibilityService controlService, String viewText, int index) {
        AccessibilityNodeInfo accessibilityNodeInfo = controlService.getRootInActiveWindow();
        if (accessibilityNodeInfo == null) {
            return null;
        }

        List<AccessibilityNodeInfo> nodeInfoList = accessibilityNodeInfo.findAccessibilityNodeInfosByText(viewText);
        if (nodeInfoList != null && !nodeInfoList.isEmpty()) {
            if (index == -1) {
                return nodeInfoList.get(nodeInfoList.size() - 1);
            } else {
                return nodeInfoList.get(index);
            }
        }
        return null;
    }


    public static List<AccessibilityNodeInfo> findViewByIds(MyAccessibilityService controlService, String funTv) {

        AccessibilityNodeInfo accessibilityNodeInfo = controlService.getRootInActiveWindow();
        if (accessibilityNodeInfo == null) {
            return null;
        }

        return accessibilityNodeInfo.findAccessibilityNodeInfosByViewId(funTv);
    }
}
